package com.ruoyi.common.utils.snowflake;

public class SnowflakeIdGenerator {
    private final long epoch = 1704067200000L; // 动态设置起点
    private final int timestampBits = 32; // 时间戳位数
    private final int machineIdBits = 8; // 增加机器 ID 位数
    private final int sequenceBits = 5; // 序列号位数不变

    private final long maxMachineId = -1L ^ (-1L << machineIdBits); // 机器 ID 最大值
    private final long sequenceMask = -1L ^ (-1L << sequenceBits); // 序列号最大值

    private long lastTimestamp = -1L; // 上一次生成 ID 的时间戳
    private long machineId; // 当前机器 ID
    private long sequence = 0L; // 当前序列号

    public SnowflakeIdGenerator(long machineId) {
        if (machineId > maxMachineId || machineId < 0) {
            throw new IllegalArgumentException("Invalid machine ID");
        }
        this.machineId = machineId;
    }

    public synchronized long nextId() {
        long timestamp = System.currentTimeMillis();

        // 检查时间戳范围
        if ((timestamp - epoch) >> timestampBits > 0) {
            throw new RuntimeException("Timestamp overflow, the ID generator has exceeded the time limit.");
        }

        // 如果是在同一毫秒内
        if (timestamp == lastTimestamp) {
            sequence = (sequence + 1) & sequenceMask; // 递增序列号
            if (sequence == 0) {
                timestamp = waitForNextMillis(timestamp); // 等待下一毫秒
            }
        } else {
            sequence = 0L; // 重置序列号
        }

        lastTimestamp = timestamp; // 更新最后时间戳

        // 组合成唯一 ID
        return ((timestamp - epoch) << (machineIdBits + sequenceBits)) | (machineId << sequenceBits) | sequence;
    }

    private long waitForNextMillis(long lastTimestamp) {
        long timestamp;
        do {
            timestamp = System.currentTimeMillis();
        } while (timestamp <= lastTimestamp);
        return timestamp;
    }
}
